package com.csu.csumall.controller.frontend;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.csu.csumall.common.ItemStatus;
import com.csu.csumall.common.UniformResponse;
import com.csu.csumall.entity.Product;
import com.csu.csumall.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

import static com.csu.csumall.common.Constant.ORIGIN;

@RestController
@RequestMapping("/api/product")
@CrossOrigin(origins = ORIGIN)
public class ProductController {

    private final IProductService productService;

    @Autowired
    public ProductController(IProductService productService) {
        this.productService = productService;
    }

    @GetMapping
    public UniformResponse getList(@RequestParam(value = "page", required = false, defaultValue = "1") Integer page,
                                   @RequestParam(value = "size", required = false, defaultValue = "56") Integer size,
                                   @RequestParam(value = "query", required = false) String query,
                                   @RequestParam(value = "category", required = false) String category) {

        QueryWrapper<Product> queryWrapper = new QueryWrapper<>();
        queryWrapper.ne("status", ItemStatus.DISABLE.getValue());

        if (null == query) {
            // TODO 返回推荐
            queryWrapper.orderByAsc("id");
        } else {
            queryWrapper.like("name", query);
        }
        if (null == category) {

        } else {
            queryWrapper.like("category_id", category);
        }

        Page<Product> productPage = new Page<>(page, size);
        IPage<Product> productIPage = productService.page(productPage, queryWrapper);
        List<Product> productList = productIPage.getRecords();
        productList.forEach(s -> {
            s.setSubtitle(null);
            s.setSubImages(null);
            s.setDetail(null);
            s.setStock(null);
            s.setCreateTime(null);
            s.setUpdateTime(null);
        });

        return UniformResponse.createForSuccess(productList);
    }


    @GetMapping("{id}")
    public UniformResponse getDetail(@PathVariable String id) {
        Product product = productService.getById(id);
        if (null == product) {
            return UniformResponse.createForError("商品不存在");
        } else {
            product.setCreateTime(null);
            product.setUpdateTime(null);
            return UniformResponse.createForSuccess(product);
        }
    }


}
